const router = require("koa-router")();
const { getUserIdByContext, getImage } = require('../token')
const CommentLiking = require('../../model/CommentLiking')
const ArticleComment = require('../../model/ArticleComment')
const UserBasic = require('../../model/UserBasic')
const UserMessage = require('../../model/UserMessage')
const { sendMessageByUserId } = require('../websocket')
const UUID = require('uuid')

// 对评论或者回复点赞
router.post('/likings', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.request.body
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target) {
    return { success: false, message: '点赞目标不能为空', status: 400 }
  }
  const likeOne = await CommentLiking.findOne({ user_id, comment_id: target }).lean()
  const commentOne = await ArticleComment.findOne({ comment_id: target }).lean()
  const userProfle = await UserBasic.findOne({ user_id: commentOne.user_id  }).lean()
    if (userProfle) {
      // 通知被关注的用户
      sendMessageByUserId(target, "comment notify", {
        user_id,
        user_name: userProfle.user_name,
        user_photo: getImage(userProfle.profile_photo),
        timestamp: new Date().getTime(),
        art_id: target
      })
      const UserInfo = await UserBasic.findOne({ user_id })
      await UserMessage.create({ message_id: UUID.v4(), title: UserInfo.user_name, content: '赞了你的评论', user_id: target, comment_target:  commentOne.content  })
    }
  if (!likeOne) {
     await CommentLiking.create({ user_id, comment_id: target })
  }
  ctx.status = 201

  return { data: { target } }
}) 
// 取消对评论或者回复点赞
router.delete('/likings/:target', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.params
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target) {
    return { success: false, message: '点赞目标不能为空', status: 400 }
  }
  await CommentLiking.findOneAndRemove({ user_id, comment_id: target }).lean()
  ctx.status = 204
})
module.exports = router.routes();
